import type { FilterStatus } from '../types/ssh'

// 验证CIDR格式
export const validateCIDR = (cidr: string): boolean => {
  const cidrRegex = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/
  if (!cidrRegex.test(cidr)) return false

  const [ip, prefix] = cidr.split('/')
  const prefixNum = parseInt(prefix)
  if (prefixNum < 0 || prefixNum > 32) return false

  const ipParts = ip.split('.')
  return ipParts.every(part => {
    const num = parseInt(part)
    return num >= 0 && num <= 255
  })
}

// 获取状态显示文本
export const getStatusText = (status: string): string => {
  switch (status) {
    case 'port_closed':
      return '端口未开启'
    case 'auth_failed':
      return '认证失败'
    case 'connected':
      return '连接成功'
    case 'sudo_supported':
      return '支持sudo'
    default:
      return '未知状态'
  }
}

// 获取状态样式类
export const getStatusClass = (status: string): string => {
  switch (status) {
    case 'port_closed':
      return 'port-closed'
    case 'auth_failed':
      return 'auth-failed'
    case 'connected':
      return 'connected'
    case 'sudo_supported':
      return 'sudo-supported'
    default:
      return ''
  }
}

// 导出CSV
export const exportToCSV = (results: any[], getStatusText: (status: string) => string) => {
  if (results.length === 0) {
    return null
  }

  // 准备CSV数据
  const headers = ['时间', '网段', '端口', '用户名', '状态', '详细信息']
  const csvData = results.map(result => [
    result.timestamp,
    result.request.network,
    result.request.port,
    result.request.username,
    getStatusText(result.status),
    result.info
  ])

  // 添加表头
  csvData.unshift(headers)

  // 转换为CSV格式
  const csvContent = csvData.map(row => row.map(cell => {
    // 处理包含逗号、引号或换行符的单元格
    if (typeof cell === 'string' && (cell.includes(',') || cell.includes('"') || cell.includes('\n'))) {
      return `"${cell.replace(/"/g, '""')}"`
    }
    return cell
  }).join(',')).join('\n')

  // 创建Blob对象
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8' })
  
  // 创建下载链接
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  
  // 设置文件名
  const now = new Date()
  const timestamp = now.toISOString().replace(/[:.]/g, '-')
  link.download = `ssh检测结果_${timestamp}.csv`
  
  return { link, url }
} 